/**
 * BBD Service Inc
 * All Rights Reserved @2018
 */
package com.xiaoke.web.controller;

import com.alibaba.fastjson.JSON;
import com.xiaoke.entity.Dictionary;
import com.xiaoke.utils.AjaxMsg;
import com.xiaoke.utils.JqgridPage;
import com.xiaoke.utils.QueryFilters;
import com.xiaoke.utils.data.PageModel;
import com.xiaoke.web.service.DictionaryService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @author
 */
@Controller

public class DictionaryController {
    @Resource
    private DictionaryService dictionaryService;

    @RequestMapping({"/dictionary/list"})
    @ResponseBody
    public List<Map<String, Object>> list(String keyNo) {
        List<Map<String, Object>> dictionaries = dictionaryService.findByKeyNo(keyNo);
        return dictionaries;
    }

    @RequestMapping(value = "/dictionary/page")
    public String list(Model model) {
        return "dictionary/list";
    }

    @RequestMapping("/dictionary/query")
    @ResponseBody
    public JqgridPage query(int page, int rows, String sidx, String sord, String filters) {
        QueryFilters filters_ = null;
        if (filters == null || filters.trim().isEmpty()) {
            filters_ = new QueryFilters();
        } else {
            filters_ = JSON.parseObject(filters, QueryFilters.class);
        }
        filters_.setSidx(sidx);
        filters_.setSord(sord);
        filters_.setPageNo(page);
        filters_.setPageSize(rows);
        PageModel pageInfo = dictionaryService.getByFilter(filters_);
        // 用JqgridPage对结果进行包装
        return new JqgridPage((long) pageInfo.getTotalRecord(), pageInfo.getTotalPage(), pageInfo.getPageNo(),
                pageInfo.getResults());
    }
    @RequestMapping("/dictionary/oper")
    @ResponseBody
    public AjaxMsg oper(HttpServletResponse response, String oper, Dictionary dictionary) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        ajaxMsg.setCode(AjaxMsg.SUCCESS);
        if (oper.equals("del")) {
            dictionaryService.delete(dictionary.getId());
        } else if (oper.equals("edit")) {
            dictionaryService.update(dictionary);
        } else if (oper.equals("add")) {
            dictionaryService.insert(dictionary);
        } else {
            ajaxMsg.setCode("500");
            ajaxMsg.setMessage("操作代码错误！系统只提供增加/修改/删除功能。");
            return ajaxMsg;
        }
        return ajaxMsg;
    }

    @RequestMapping("/dictionary/delete")
    public AjaxMsg delete(int[] ids) {
        for (int id : ids) {
            dictionaryService.delete(id);
        }
        return new AjaxMsg();
    }
}
